//
//  OCSSWriteOrderInfoPage.swift
//  OCSSStoreSwift
//
//  Created by MacMiniKangChe on 2018/10/16.
//  Copyright © 2018年 MacMiniKangChe. All rights reserved.
//

import UIKit
import HandyJSON
import SwiftyJSON

class OCSSWriteOrderInfoPage: OCSSBaseViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet var tbFooterView: UIView!
    
    @IBOutlet weak var customerNameTF: UITextField!//用户名
    @IBOutlet weak var phoneTF: UITextField!//电话
    @IBOutlet weak var recommendTF: UITextField!//推荐码
    @IBOutlet weak var IDCardTF: UITextField! //身份证号
    @IBOutlet weak var creditCodeTF: UITextField! //
    @IBOutlet weak var totalPriceLab: UILabel!  //商品总价
    @IBOutlet weak var discountsTF: UITextField! //优惠
    @IBOutlet weak var remarkTF: UITextField! //备注
    @IBOutlet weak var receiveMoneyTypeTF: UITextField! //收款方式
    @IBOutlet weak var getGoodsTypeTF: UITextField! //收货方式
    
    var selectCars:[OCSSOverBookModel]?;
    var selectPayType:[String:String]?;
    var selectReceiveType:[String:String]?;
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "填写订单";
        navigationController?.navigationBar.tintColor = UIColor.black;
        self.regTableViewNib(tableView: tableView, className: OCSSWriteOrderInfoCell.className());
        tableView.tableFooterView = tbFooterView;
        
    }
    
    @IBAction func gatheringTypeButtonEvent(_ sender: UIButton) {
        let actionSheet = UIAlertController.init(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet);
        let titles = [["type":"现金","id":"10"],
                      ["type":"微信","id":"20"],
                      ["type":"支付宝","id":"30"],
                      ["type":"转账","id":"60"],
                      ["type":"取消","id":"0"]];
        for title in titles {
            var action:UIAlertAction;
            
            if title["type"] == "取消"{
                 action = UIAlertAction.init(title: title["type"], style: UIAlertActionStyle.cancel) { (alert) in
                    
                }
            }else{
                action = UIAlertAction.init(title: title["type"], style: UIAlertActionStyle.default) { (alert) in
                    self.selectPayType = title;
                    self.receiveMoneyTypeTF.text = title["type"];
                }
            }
            actionSheet.addAction(action);
        }
        present(actionSheet, animated: true, completion: nil);
    }
    
    @IBAction func getTypeButtonEvent(_ sender: UIButton) {
        let actionSheet = UIAlertController.init(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet);
        let titles = [["type":"现货","id":"10"],
                      ["type":"订货","id":"30"],
                      ["type":"取消","id":"0"]];
        for title in titles {
            var action:UIAlertAction;
            
            if title["type"] == "取消"{
                action = UIAlertAction.init(title: title["type"], style: UIAlertActionStyle.cancel) { (alert) in
                    
                }
            }else{
                action = UIAlertAction.init(title: title["type"], style: UIAlertActionStyle.default) { (alert) in
                    self.selectReceiveType = title;
                    self.getGoodsTypeTF.text = title["type"];
                }
            }
            actionSheet.addAction(action);
        }
        present(actionSheet, animated: true, completion: nil);
    }
    //MARK:订单提交按钮点击
    @IBAction func submitButtonEvent(_ sender: UIButton) {
        let items = NSMutableArray.init();
        for model in selectCars! {
            let str = model.toJSONString();
            let jsonData:Data = str!.data(using: .utf8)!;
            let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
            if dict != nil {
                items.add(dict as! NSDictionary);
            }
        }
        let params = ["CustomerName":customerNameTF.text ?? "",
                      "DistributionType":selectReceiveType?["id"] ?? "",
                      "EnterpriseId":"",
                      "Invoice":"",
                      "MobilePhoneNumber":phoneTF.text ?? "",
                      "OrderAmount":totalPriceLab.text ?? "",
                      "OrderDiscount":discountsTF.text ?? "",
                      "PayAmount":"",
                      "PayType":selectPayType?["id"] ?? "",
                      "Remarks":remarkTF.text ?? "",
                      "UserId":"",
                      "Items":items
            ] as [String : Any];
        
        OCSSNetRequest.requestData(url: "/PlaceOrder/Save_app", para: params , type: MethodType.post, success: { (result) in
            let resDic = JSON(result).dictionaryObject;
            if JSON(resDic!["Status"]!).boolValue {
                let orderId = resDic!["Data"] as! String;
                let completePage = OCSSCompleteOrderPage.init();
                completePage.orderId = orderId;
                self.navigationController?.pushViewController(completePage, animated: true);
            }else{
                print(resDic!["Message"]!);
            }
        }) { (error) in
            print(error);
        };
        
    }
//    MARK:TableViewDelegate && TableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (selectCars?.count)!;
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "OCSSWriteOrderInfoCell") as! OCSSWriteOrderInfoCell;
        cell.model = (selectCars?[indexPath.row] as! OCSSOverBookModel);
        
        return cell;
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 110;
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 14;
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    


}
